/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.ui.base.BaseDialog;
import com.ouertech.android.agm.lib.ui.base.MenuTxt;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.Shop;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.CartProductAdapter;
import com.simon.mengkou.ui.dialog.CommonConfirmDialog;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/23.
 * desc    : 我的购物车界面
 */
public class CartActivity extends BaseTopActivity {
    //列表
    @Bind(R.id.cart_id_list)
    ListView mLvList;
    //全选
    @Bind(R.id.cart_id_select_all)
    TextView mTvSelectAll;
    //底部
    @Bind(R.id.cart_id_bottom_root)
    RelativeLayout mRlBottom;
    //结算or删除
    @Bind(R.id.cart_id_pay)
    TextView mTvPay;
    //总计
    @Bind(R.id.cart_id_total)
    TextView mTvTotal;


    //店铺图片
    SimpleDraweeView mSdvAvatar;
    //店铺名
    TextView mTvName;

    //运费
    TextView mTvFreight;
    //小计
    TextView mTvAmount;

    private CartProductAdapter mAdapter;

    private MenuTxt mMenuEdit;
    private MenuTxt mMenuFinish;
    private boolean mIsSelectAll;
    private Shop mShop;

    @Override
    protected void initTop() {
        setTitle(R.string.cart_title);
        setNavigation(R.drawable.common_ic_left_nav);

        //编辑
        mMenuEdit = new MenuTxt.MenuTxtBuilder(this)
                .setTitle(R.string.cart_edit)
                .setListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        hideMenu(mMenuEdit);
                        addMenu(mMenuFinish);
                        mTvPay.setText(R.string.common_delete);
                        mAdapter.setEditable(true);
                        mAdapter.notifyDataSetChanged();
                        mTvTotal.setVisibility(View.GONE);
                        mTvSelectAll.setVisibility(View.VISIBLE);
                        return false;
                    }
                }).build();

        //完成
        mMenuFinish = new MenuTxt.MenuTxtBuilder(this)
                .setTitle(R.string.cart_finish)
                .setListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        hideMenu(mMenuFinish);
                        addMenu(mMenuEdit);
                        mTvPay.setText(R.string.cart_pay);
                        mAdapter.setEditable(false);
                        mAdapter.notifyDataSetChanged();
                        mTvTotal.setVisibility(View.VISIBLE);
                        mTvSelectAll.setVisibility(View.GONE);
                        return false;
                    }
                }).build();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_cart);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        registerAction(CstOuer.BROADCAST_ACTION.CART_SELECT_ALL_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.ORDER_SUBMIT_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.DELETE_CART_ACTION);

        //头部
        View header = LayoutInflater.from(this).inflate(R.layout.layout_cart_header, null);
        mSdvAvatar = (SimpleDraweeView) header.findViewById(R.id.cart_id_avatar);
        mTvName = (TextView) header.findViewById(R.id.cart_id_name);
        mLvList.addHeaderView(header);

        //尾部
        View footer = LayoutInflater.from(this).inflate(R.layout.layout_cart_footer, null);
        mTvFreight = (TextView) footer.findViewById(R.id.order_detail_id_freight);
        mTvAmount = (TextView) footer.findViewById(R.id.order_detail_id_discount);
        mLvList.addFooterView(footer);

        mAdapter = new CartProductAdapter(this);
        mLvList.setAdapter(mAdapter);

        //失败重试
        setOnRetryListener(new OnRetryListener() {
            @Override
            public void onRetry() {
                getCartList();
            }
        });

        //获取数据
        getCartList();

    }

    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        //全选
        if(CstOuer.BROADCAST_ACTION.CART_SELECT_ALL_ACTION.equals(intent.getAction())) {
            mIsSelectAll = intent.getBooleanExtra(CstOuer.KEY.SELECTALL, false);
            if(mIsSelectAll) {
                mTvSelectAll.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_ic_select_pressed, 0, 0, 0);
            } else {
                mTvSelectAll.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_ic_select_normal, 0, 0, 0);
            }

//            computeTotalPrice();
        } else if(CstOuer.BROADCAST_ACTION.ORDER_SUBMIT_ACTION.equals(intent.getAction())) {
            getCartList();
        } else if(CstOuer.BROADCAST_ACTION.DELETE_CART_ACTION.equals(intent.getAction())) {
            regetCartList();
        }
    }

    /**
     * 获取订单详情
     */
    private void getCartList() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cartList(
                OuerApplication.mUser.getUserId(),
                new OuerFutureListener(this){

                    public void onStart(AgnettyResult result) {
                        setLoading(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setLoading(false);
                        List<Shop> datas = (List<Shop>) result.getAttach();

                        if(UtilList.isNotEmpty(datas)) {
                            mShop = datas.get(0);

                            //显示编辑
                            addMenu(mMenuEdit);
                            hideMenu(mMenuFinish);
                            mRlBottom.setVisibility(View.VISIBLE);
                            mTvTotal.setVisibility(View.VISIBLE);
                            mTvTotal.setText(getString(R.string.common_price,
                                    UtilOuer.formatPrice(0)));
                            mTvSelectAll.setVisibility(View.GONE);

                            //店铺图片
                            OuerApplication.mImageLoader.loadAvatar(mSdvAvatar, mShop.getAvatar());
                            //店铺名
                            mTvName.setText(mShop.getShopName());
                            //运费
                            mTvFreight.setText(getString(R.string.common_price,
                                    UtilOuer.formatPrice(mShop.getFreight())));
                            //小计
//                            mTvAmount.setText(getString(R.string.common_price,
//                                    UtilOuer.formatPrice(0)));

                            mAdapter.setList(mShop.getGoodsList());
                            computeTotalPrice();
                        } else {
                            //暂无数据
                            setEmptyText(R.string.common_empty_data);
                            hideMenu(mMenuEdit);
                            hideMenu(mMenuFinish);
                            mRlBottom.setVisibility(View.GONE);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setRetry(true);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setRetry(true);
                    }
                });

        attachDestroyFutures(future);
    }


    /**
     * 获取订单详情
     */
    private void regetCartList() {
        AgnettyFuture future = OuerApplication.mOuerFuture.cartList(
                OuerApplication.mUser.getUserId(),
                new OuerFutureListener(this){

                    public void onStart(AgnettyResult result) {

                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);

                        List<Shop> datas = (List<Shop>) result.getAttach();

                        if(UtilList.isNotEmpty(datas)) {
                            mShop = datas.get(0);

                            //显示编辑
                            hideMenu(mMenuEdit);
                            addMenu(mMenuFinish);
                            mRlBottom.setVisibility(View.VISIBLE);
                            mTvTotal.setVisibility(View.GONE);
                            mTvTotal.setText(getString(R.string.common_price,
                                    UtilOuer.formatPrice(0)));
                            mTvSelectAll.setVisibility(View.VISIBLE);

                            //店铺图片
                            OuerApplication.mImageLoader.loadAvatar(mSdvAvatar, mShop.getAvatar());
                            //店铺名
                            mTvName.setText(mShop.getShopName());
                            //运费
                            mTvFreight.setText(getString(R.string.common_price,
                                    UtilOuer.formatPrice(mShop.getFreight())));
                            //小计
//                            mTvAmount.setText(getString(R.string.common_price,
//                                    UtilOuer.formatPrice(0)));

                            mAdapter.setList(mShop.getGoodsList());
                            computeTotalPrice();
                        } else {
                            //暂无数据
                            setEmptyText(R.string.common_empty_data);
                            hideMenu(mMenuEdit);
                            hideMenu(mMenuFinish);
                            mRlBottom.setVisibility(View.GONE);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                       // super.onNetUnavaiable(result);

                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);

                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 是否全选
     */
    @OnClick(R.id.cart_id_select_all)
    public void selectAll() {
        mIsSelectAll = !mIsSelectAll;

        if(mIsSelectAll) {
            mTvSelectAll.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_ic_select_pressed, 0, 0, 0);
        } else {
            mTvSelectAll.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_ic_select_normal, 0, 0, 0);
        }

        List<Product> datas = mAdapter.getData();
        if(UtilList.isNotEmpty(datas)) {
            for(Product p : datas) {
                p.setSelected(mIsSelectAll);
            }
        }

//        computeTotalPrice();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 结算or删除
     */
    @OnClick(R.id.cart_id_pay)
    public void pay() {
        //编辑状态-》删除
        if(mAdapter.isEditable()) {
            List<Product> datas = mAdapter.getData();
            final List<Product> newDatas = new ArrayList<>();
            final List<Product> delDatas = new ArrayList<>();

            if(UtilList.isNotEmpty(datas)) {
                for(Product p : datas) {
                    if(p.isSelected()) {
                        delDatas.add(p);
                    } else {
                        newDatas.add(p);
                    }
                }

                if(UtilList.isNotEmpty(delDatas)) {
                    new CommonConfirmDialog(this, R.string.cart_product_delete_tips,
                            new BaseDialog.OnLeftListener() {
                                @Override
                                public void onLeft() {
//                                    cartEdit(delDatas);

                                    AgnettyFuture future = OuerApplication.mOuerFuture.deleteCart(delDatas, null);
                                    attachDestroyFutures(future);

                                    if(UtilList.isNotEmpty(newDatas)) {
                                        mAdapter.setList(newDatas);
//                                        mTvAmount.setText(getString(R.string.common_price,
//                                                UtilOuer.formatPrice(0)));
//                                        mTvTotal.setText(Html.fromHtml(getString(R.string.cart_total,
//                                                UtilOuer.formatPrice(0))));
                                        computeTotalPrice();
                                    } else {
                                        setEmptyText(R.string.common_empty_data);
                                        hideMenu(mMenuEdit);
                                        hideMenu(mMenuFinish);
                                    }
                                }
                            }).show();

                } else {
                    UtilOuer.toast(this, R.string.cart_product_delete_empty);
                    return;
                }


            }
        } else{//结算
            Shop shop = new Shop();
            shop.setShopId(mShop.getShopId());
            shop.setAvatar(mShop.getAvatar());
            shop.setFreight(mShop.getFreight());
            shop.setShopName(mShop.getShopName());

            List<Product> datas = mAdapter.getData();
            shop.setGoodsList(datas);
//            OuerDispatcher.presentOrderConfirmActivity(this, shop);

//            final List<Product> newDatas = new ArrayList<>();
//
//
//            if(UtilList.isNotEmpty(datas)) {
//                for (Product p : datas) {
//                    if (p.isSelected()) {
//                        newDatas.add(p);
//                    }
//                }
//            }
//
//            if(UtilList.isNotEmpty(newDatas)) {
//                shop.setGoodsList(newDatas);
//                OuerDispatcher.presentOrderConfirmActivity(this, shop);
//            } else {
//                UtilOuer.toast(this, R.string.cart_product_pay_empty);
//            }
        }
    }


//    private void cartEdit(final List<Product> products) {
//        if(UtilList.isEmpty(products)) {
//            regetCartList();
//        } else {
//            Product p = products.get(0);
//            AgnettyFuture future = OuerApplication.mOuerFuture.cartEdit(
//                    p.getId(), 0, p.getOrderItemId(), new OuerFutureListener(this){
//                        @Override
//                        public void onComplete(AgnettyResult result) {
//                            super.onComplete(result);
//                            products.remove(0);
//                            cartEdit(products);
//                        }
//                    });
//            attachDestroyFutures(future);
//        }
//    }


    /**
     * 计算总价格
     */
    private void computeTotalPrice() {
        double price = 0;
        List<Product> datas = mAdapter.getData();
        if(UtilList.isNotEmpty(datas)) {
            boolean flag = false;
            for(Product p : datas) {
//                if(p.isSelected()) {
                    flag = true;
                    price += p.getPrice() * p.getCount();
//                }
            }

            if(flag) {
                price += mShop.getFreight();
            }
        }

        mTvAmount.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(price)));

        mTvTotal.setText(Html.fromHtml(getString(R.string.cart_total,
                UtilOuer.formatPrice(price))));
    }
}
